package com.hxkj.client.service.taglib.directive;

import com.hxkj.client.service.ArticleServiceClient;
import com.hxkj.client.service.ColumnServiceClient;
import com.hxkj.client.service.OptionColumnServiceClient;
import com.hxkj.domain.context.EnvironmentContextHolder;
import com.hxkj.domain.enums.ColumnExceptionEnum;
import com.hxkj.domain.po.Article;
import com.hxkj.domain.po.Column;
import com.hxkj.domain.po.OptionColumnTree;
import com.hxkj.domain.po.WebsiteAddr;
import com.hxkj.utils.TemplateModelUtils;
import com.platform.common.domain.exception.CustomException;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Writer;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static com.hxkj.client.service.taglib.config.LableConstant.CMS_COLUMN_ID;

/**
 * @ClassName ColumnTreeDirective 单个分类及其下级分类树封装文章标签解析
 * @Description TODO
 * @Author Mr.zheng
 * @Date 2018/8/21 11:08
 * @Version 1.0
 */
@Component
@Log4j
public class ColumnTreeDirective extends AbstractDirective {
    @Autowired
    private OptionColumnServiceClient optionColumnServiceClient;

    @Autowired
    private ColumnServiceClient columnServiceClient;

    @Autowired
    private ArticleServiceClient articleServiceClient;

    /**
     * 输入参数，分类ID
     */
    public static final String COLUMN_ID = "columnId";
    /**
     * 输入参数，站点ID
     */
    public static final String SITE_ID = "siteId";
    /**
     * 输入参数，是否排序,0：升序，1：降序
     */
    public static final String SORT = "sort";
    /**
     * 输入参数，获取起始条数
     */
    public static final String START = "start";
    /**
     * 输入参数，获取参数条数
     */
    public static final String COUNT = "count";
    /**
     * 输入参数，排序的字段，多个用","隔开
     */
    public static final String LOCATION_LEVEL = "locationLevel";

    /**
     * 输入参数，标题字数长度，多余的用"...."替代
     */
    public static final String TITLELEN = "titleLen";
    /**
     * 输入参数，是只查有图片的文章 0、为需要显示图片 1、为不需要显示图片
     */
    public static final String SHOW_IMG = "showImg";


    /**
     * 分类内容
     */
    public static final String COLUMN_TREE = "columnTree";


    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        env.getOut();
        try {
            //Mr.zheng:获取参数
            Long columnId = super.getLong(COLUMN_ID, params) == null ? (Long) getCustomAttrbute(env, "columnId") : super.getLong(COLUMN_ID, params);
            Long siteId = super.getLong(SITE_ID, params);
            siteId = siteId == null ? (Long) getCustomAttrbute(env, SITE_ID) : siteId;
            //Mr.zheng:默认根据降序排序
            String sort = super.getString(SORT, params) == null ? "update_time DESC" : super.getString(SORT, params);
            //Mr.zheng:默认取5条文章
            int start = super.getInt(START, params) == null ? 1 : super.getInt(START, params);
            //Mr.zheng:默认取5条文章
            int count = super.getInt(COUNT, params) == null ? 5 : super.getInt(COUNT, params);
            //Mr.zheng:默认取20字节
            int titleLen = super.getInt(TITLELEN, params) == null ? 20 : super.getInt(TITLELEN, params);
            //Mr.zheng:默认文章推荐等级不设置则为-1
            int locationLevel = super.getInt(LOCATION_LEVEL, params) == null ? -1 : super.getInt(LOCATION_LEVEL, params);
            //Mr.zheng:显示图片与否：默认为1不显示
            int showImg = super.getInt(SHOW_IMG, params) == null ? 1 : super.getInt(SHOW_IMG, params);
            String note = super.getNote(env);
            if (columnId == null) {
                log.info("分类ID为空");
            }
            Map<String, Object> enviroment = EnvironmentContextHolder.getEnvironment();
            Map<Long, String> siteCtxMap = (Map<Long, String>) enviroment.get("siteCtxMap");
            String urlContext = siteCtxMap.get(siteId);
            Column column = new Column();
            column.setColumnId(columnId);
            column.setSiteId(siteId);
            //Mr.zheng:封装当前选中的分类信息
            column = columnServiceClient.getColumn(column);

            WebsiteAddr websiteAddr = getWebSiteAddr(siteId);

            OptionColumnTree columnTree;
            if (column != null) {
                if (StringUtils.isNotBlank(note)) {
                    column.setManuscriptPath(websiteAddr.getIpAdd() + column.getManuscriptPath());
                }else {
                    // 静态文件分类及下级文章链接加前缀
                    if (StringUtils.isNotBlank(urlContext)) {
                        column.setManuscriptPath(urlContext + column.getManuscriptPath());
                    }
                }
                column.setSort(sort);
                column.setCount(count);
                column.setTitleLen(titleLen);
                column.setChecked(showImg);
                columnTree = optionColumnServiceClient.getColumnTree(column);
            } else {
                if (StringUtils.isNotBlank(note)) {
                    column.setManuscriptPath(websiteAddr.getIpAdd() + column.getManuscriptPath());
                }else {
                    // 静态文件分类及下级文章链接加前缀
                    if (StringUtils.isNotBlank(urlContext)) {
                        column.setManuscriptPath(urlContext + column.getManuscriptPath());
                    }
                }
                column.setColumnId(columnId);
                column.setSiteId(siteId);
                column.setSort(sort);
                column.setCount(count);
                column.setTitleLen(titleLen);
                column.setChecked(showImg);
                columnTree = optionColumnServiceClient.getColumnTree(column);
            }

            if (StringUtils.isNotBlank(note)) {
                columnTree.setManuscriptPath(websiteAddr.getIpAdd() + columnTree.getManuscriptPath());
                for (OptionColumnTree octe : columnTree.getChildren()) {
                    octe.setManuscriptPath(websiteAddr.getIpAdd() + octe.getManuscriptPath());
                    for (Article article : octe.getArticleList()) {
                        article.setManuscriptPath(websiteAddr.getIpAdd() + article.getManuscriptPath());
                    }
                }
            }else {
                // 静态文件分类及下级文章链接加前缀
                if(StringUtils.isNotBlank(urlContext)) {
                    columnTree.setManuscriptPath(urlContext + columnTree.getManuscriptPath());
                    for (OptionColumnTree octe : columnTree.getChildren()) {
                        octe.setManuscriptPath(urlContext + octe.getManuscriptPath());
                        for (Article article : octe.getArticleList()) {
                            article.setManuscriptPath(urlContext + article.getManuscriptPath());
                        }
                    }
                }
            }

            Article article = new Article();
            if (locationLevel > 0) {
                article.setLocationLevel(locationLevel);
                article.setSiteId(siteId);
                article.setSort(sort);
                article.setStart(start - 1);
                article.setCount(count);
                article.setShowImg(showImg);
                List<Article> articleList = articleServiceClient.getArticleListByParam(article);
                if (StringUtils.isNotBlank(note)) {
                    for (Article art : articleList) {
                        art.setManuscriptPath(websiteAddr.getIpAdd() + art.getManuscriptPath());
                    }
                }else {
                    // 静态文件分类及下级文章链接加前缀
                    if(StringUtils.isNotBlank(urlContext)) {
                        for (Article art : articleList) {
                            art.setManuscriptPath(urlContext + art.getManuscriptPath());
                        }
                    }
                }
                columnTree.setArticlePush(articleList);
            }
            env.setVariable(COLUMN_TREE, DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(columnTree));

            String userToken = super.getUserToken(env);
            Writer out = env.getOut();
            if (body != null) {
                if (StringUtils.isEmpty(note)) {
                    body.render(env.getOut());
                } else {
                    Map<String, String> maps = new LinkedHashMap<>();

                    maps.put(CMS_COLUMN_ID, "");
                    maps.put(SITE_ID, String.valueOf(super.getLong(SITE_ID, params)));
                    maps.put(COLUMN_ID, String.valueOf(super.getLong(COLUMN_ID, params)));
                    maps.put(COUNT, String.valueOf(super.getInt(COUNT, params)));
                    maps.put(LOCATION_LEVEL, String.valueOf(super.getInt(LOCATION_LEVEL, params)));
                    maps.put(SHOW_IMG, String.valueOf(super.getInt(SHOW_IMG, params)));
                    maps.put(SORT, String.valueOf(super.getString(SORT, params)));
                    maps.put(START, String.valueOf(super.getInt(START, params)));
                    try {
                        super.print(body, maps, env, userToken, params);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                throw new RuntimeException("分类所在模板至少要加一个空格");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

